//
//  ZhLocation.swift
//  Uber
//
//  Created by 朱 桓 on 16/1/10.
//  Copyright © 2016年 zhu.huan. All rights reserved.
//

import UIKit
import CoreLocation

class ZhLocation: NSObject,CLLocationManagerDelegate {
    var manager:CLLocationManager!
    
    /**
    *开启定位
    */
    func startLocation()
    {
        // 判定定位操作是否被允许
        if CLLocationManager.locationServicesEnabled() {
            // 实例化定位管理器
            manager = CLLocationManager()
            // 设置代理
            manager.delegate = self
            // 定位精度
            manager.desiredAccuracy = kCLLocationAccuracyBest
            // 设置最小距离
            manager.distanceFilter = 100
            
            //  ios8特性，请求用户权限，分为：只在前台开启定位，在后台也可定位
            if UIDevice.currentDevice().systemVersion >= "8.0" {
                if #available(iOS 8.0, *) {
                    //manager.requestWhenInUseAuthorization()// 只在前台开启定位
                    manager.requestAlwaysAuthorization() // 在后台也可定位
                } else {
                    // Fallback on earlier versions
                }
            }
            // ios9新特性，将允许出现这种场景，同一app中多个location manager：一些只能在前台定位，另一些可在后台定位（并可随时禁止其后台定位）
            if UIDevice.currentDevice().systemVersion >= "9.0" {
                if #available(iOS 9.0, *) {
                    manager.allowsBackgroundLocationUpdates = true
                } else {
                    // Fallback on earlier versions
                }
            }
            // 更新用户位置
            manager.startUpdatingLocation()
        }
    }

    /**
    *定位失败，回调此方法
    */
    func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
        ptLog("location error : \(error.code)")
    }
    
    func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus)
    {
        //ptLog(String(status))
        if #available(iOS 8.0, *) {
            if status == CLAuthorizationStatus.AuthorizedAlways {
                ptLog("AuthorizedAlways")
            } else if status == CLAuthorizationStatus.AuthorizedWhenInUse {
                ptLog("AuthorizedWhenInUse")
            }
        } else {
            // Fallback on earlier versions
        }
    }

    /**
    *实现反地理编码
    */
    func searchAddress(location:CLLocation)
    {
        let coder:CLGeocoder = CLGeocoder()
        coder.reverseGeocodeLocation(location) { (marks, error) -> Void in
            if marks != nil {
                for mark in marks! {
                    ptLog(mark.name!)
                    print(mark.location!.coordinate)
                }
            }
        }
    }
    
    func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {
        searchAddress(newLocation)
    }
    
    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        searchAddress(locations.last!)
        
        // 停止更新位置（如果定位服务不需要实时刷新的话，那么应该停止位置的更新）
        manager.stopUpdatingLocation()
    }
}
